package cn.peifu.hrm.service.impl;

import cn.peifu.hrm.domain.Login;
import cn.peifu.hrm.exception.GlobalException;
import cn.peifu.hrm.mapper.LoginMapper;
import cn.peifu.hrm.service.ILoginService;
import cn.peifu.hrm.to.Loginto;
import cn.peifu.hrm.util.HttpClientUtils;
import cn.peifu.hrm.vo.AccessTokenVo;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

/**
 * <p>
 * 登录表 服务实现类
 * </p>
 *
 * @author xie
 * @since 2021-08-16
 */
@Service
public class LoginServiceImpl extends ServiceImpl<LoginMapper, Login> implements ILoginService {

    @Override
    public Login save(Loginto loginto) {
        Login login = new Login();
        BeanUtils.copyProperties(loginto,login);
        login.setEnabled(true);
        super.insert(login);
        return login;
    }

    @Override
    public AccessTokenVo login(Login login) {
        String url = "http://localhost:1050/oauth/token?client_id=%s&client_secret=%s&grant_type=password&username=%s&redirect_uri=http://www.baidu.com&password=%s";
        Integer type = login.getType();
        String client_id = "admin";
        String client_secret = "123";
        if(type == 0 || type == 1){
            client_id = "admin";
        }else if(type == 2){
            client_id = "website";
        }
        //1.拼接认证服务的url
        String format = String.format(url, client_id, client_secret, login.getUsername(), login.getPassword());
        //2.使用HttpClient调用认证服务
        String httpPost = HttpClientUtils.httpPost(format, null);
        //3.将返回的结果封装成AccessTokenVo
        if (!StringUtils.hasLength(httpPost)){
            throw new GlobalException("登录失败！");
        }
        AccessTokenVo accessTokenVo = JSON.parseObject(httpPost, AccessTokenVo.class);
        return accessTokenVo;
    }
}
